<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<video autoplay controls id="local" style="width: 200px;"></video>
<video autoplay controls id="remote"></video>
<button id="start">开始</button>
<script src="./socket.io.min.js"></script>
<script src="./socket.js"></script>
<script>
  const $local = document.querySelector('#local');
  const $remote = document.querySelector('#remote');
  const $start = document.querySelector('#start');
  let pc;

  const socket = useSocket(userA, () => {
    /**
     * 收到对端消息
     */
    socket.on('message:ice', ({ data }) => {
      const ice = new RTCIceCandidate(data)
      console.log('收到:ice => ', ice)
      pc.addIceCandidate(ice)
    })

    socket.on('message:answer', ({ data }) => {
      console.log('收到:answer => ', data)
      pc.setRemoteDescription(data)
    })
  })

  /**
   * 获取到本机 ICE，发送给对端
   *
   * @param event
   */
  function onIceCandidate (event) {
    if (event.candidate) {
      const candidate = event.candidate.toJSON()
      console.log('发送：ice', event.candidate)

      socket.emit('message:ice', { member: userB, data: candidate })
    }
  }

  /**
   * 创建 WebRTC
   */
  function startWebRTC() {
    const { mediaDevices } = navigator
    const configuration = {
      iceServers: [
        {'urls': 'stun:stun.stunprotocol.org:3478'},
        {'urls': 'stun:stun.l.google.com:19302'},
      ]
    };

    /**
     * 打开本机摄像头和麦
     * 播放本地流
     */
    return mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {
      pc = new RTCPeerConnection(configuration)

      // 监听 ICE
      pc.addEventListener('icecandidate', onIceCandidate)
      /**
       * 获取到对端的 流
       *
       * @param event
       */
      pc.ontrack = (event) => {
        console.log('ontrack： 收到对端的流，打开对端视频 ')
        if ($remote.srcObject) return;
        $remote.srcObject = event.streams[0];
      };

      return stream
    }).then((stream) => {
      // 获取到本地流
      $local.srcObject = stream
      console.log('getUserMedia： 获取到本地流，打开本地视频 ')
      stream.getTracks().forEach((track) => {
        console.log('getTracks： 添加本地轨道到 webrtc 通道 ', track)
        pc.addTrack(track, stream);
      });
    })
  }

  function call () {
    const offerOptions = {
      offerToReceiveAudio: 1,
      offerToReceiveVideo: 1
    };
    // 打开摄像头
    // 创建WebRTC
    startWebRTC ().then(_ => {
      console.log('开始')
      /**
       * 创建本地描述信息
       */
      pc.createOffer(offerOptions).then(function(offer) {
        console.log('创建 Offer', offer)
        /**
         * 保存本地描述信息
         */
        return pc.setLocalDescription(offer);
      }).then(function() {
        const { sdp } = pc.localDescription
        console.log('发送 Offer')
        /**
         * 发送本地描述信息到对端
         */
        socket.emit('message:offer', { member: userB, data: { type: "offer", sdp: sdp }})
      }).catch(function(reason) {
        // 错误处理
      });
    })
  }

  $start.addEventListener('click', call, false)
</script>
</body>
</html>
